<!-- 进货退货新增界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">基础信息</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-form :model="purtform" :rules="rules" ref="purtref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="退货单号" prop="code">
                        <el-input placeholder="自动获取编号" style="width: 300px;" v-model="purtform.code" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="退货日期" prop="date">
                        <el-date-picker
                            v-model="purtform.date"
                            type="datetime"
                            placeholder="请选择"
                            format="YYYY-MM-DD HH:mm:ss"
                            date-format="MMM DD, YYYY"
                            time-format="HH:mm"
                            style="width: 300px;"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
             <el-row>
                <el-col :span="11">
                    <el-form-item label="进货单号" prop="purcode">
                        <el-input placeholder="请选择" style="width: 300px;" v-model="purtform.purcode" readonly>
                            <template #append>
                                <el-button @click="ShowPurchaseOrderDialog">...</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="供应商" prop="supname">
                        <el-input placeholder="请选择进货单" style="width: 300px;" v-model="purtform.supname" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="联系人" prop="suplink">
                        <el-input placeholder="请选择进货单" style="width: 300px;" v-model="purtform.suplink" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="联系方式" prop="supphone">
                        <el-input placeholder="请选择进货单" style="width: 300px;" v-model="purtform.supphone" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="进货部门" prop="deptname">
                        <el-input placeholder="请选择进货单" style="width: 300px;" v-model="purtform.deptname" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="进货人" prop="username">
                        <el-input placeholder="请选择进货单" style="width: 300px;" v-model="purtform.username" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                     <el-form-item label="退货原因" prop="reason">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="purtform.reason">
                           <el-option label="不想要了" value="不想要了"></el-option>
                           <el-option label="质量问题" value="质量问题"></el-option>
                           <el-option label="其他" value="其他"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" placeholder="请输入" v-model="purtform.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>


     <!--退货明细-->
     <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">退货明细</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <div style="text-align: left;margin-left: 20px;">
            <el-button type="success" @click="ShowProduct">添加</el-button>
            <el-button @click="batchRemoveProducts">移除</el-button>
        </div>
        <!--表格-->
        <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column fixed type="index" label="序号" width="60"></el-table-column>
            <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
            <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
            <el-table-column prop="type_name" label="货品类型" width="100"></el-table-column>
            <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
            <el-table-column prop="proc_primary_unit" label="单位" width="70"></el-table-column>
            <el-table-column prop="proc_pur_num" label="进货数量"></el-table-column>
            <el-table-column prop="in_stock_num" label="已入库"></el-table-column>
            <el-table-column prop="not_in_stock_num" label="未入库"></el-table-column>
            <el-table-column label="本次退货数量" width="150">
                <template #default="scope">
                    <el-input-number v-model="scope.row.purtd_num" :min="0" :max="scope.row.proc_pur_num" @change="calculateAmount(scope.row)" style="width: 120px;"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="purt_price" label="进货单价" width="100">
                <template #default="scope">
                    {{ scope.row.purt_price ? Number(scope.row.purt_price).toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column prop="purtd_total" label="退货金额"></el-table-column>
            <el-table-column prop="remark" label="备注" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" style="width: 120px;"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                    <el-button type="danger" size="small" text="移除" @click="removeProduct(scope.row.proc_id)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 汇总信息 -->
        <div style="display: flex; justify-content: flex-end; margin-top: 15px; padding-right: 20px;">
            <div style="text-align: right;">
                <span style="margin-right: 20px;">退货种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                <span style="margin-right: 20px;">退货数量: <b style="color: red;">{{ calculateTotalQuantity() }}</b></span>
                <span>总金额: <b style="color: red;">{{ calculateTotalAmount() }}</b></span>
            </div>
        </div>
    </div>



    <!--上传附件-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">上传附件</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                    </div>
                </template>
        </el-upload>
    </div>


    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
        <el-button @click="SaveAsDraft">保存为草稿</el-button>
        <el-button @click="OKAdd">保存并新增</el-button>
        <el-button type="primary" @click="OK">保存</el-button>
    </div>


    <!--选择进货单模态框-->
    <el-dialog v-model="purchaseOrderDialogVisible" title="选择进货单" width="800" close-on-click-modal="false">
        <!--表格-->
        <el-table :data="purdata" stripe height="400" border highlight-current-row @selection-change="selectOrder">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="pur_code" label="进货单号" width="200"></el-table-column>
                <el-table-column prop="pur_status" label="单据状态" width="120"></el-table-column>
                <el-table-column prop="pur_date" label="进货日期" width="200"></el-table-column>
                <el-table-column prop="sup_name" label="供应商" width="150"></el-table-column>
                <el-table-column prop="pur_depName" label="进货部门" width="150"></el-table-column>
                <el-table-column prop="pur_userName" label="进货人" width="150"></el-table-column>
                <el-table-column prop="pur_num" label="货品数量" width="150"></el-table-column>
                <el-table-column prop="pur_total" label="进货金额" width="150"></el-table-column>
            </el-table>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="purchaseOrderDialogVisible = false">取消</el-button>
                <el-button type="success" @click="confirmPurchaseOrderSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--选择货品模态框-->
    <el-dialog v-model="productDialogVisible" title="添加货品" width="850" close-on-click-modal="false">
        <div style="font-weight: bold; margin-bottom: 10px;">
            进货单号: {{ purtform.purcode }} | 进货日期: {{ purtform.purdate }} | 供应商: {{ purtform.supname }} | 金额: {{ purtform.purtotal }} | 数量: {{ purtform.purnum }}
        </div>
        <div>
            <el-table :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="proc_pur_price" label="进货单价" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_price ? Number(scope.row.proc_pur_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="proc_pur_num" label="进货数量" width="100"></el-table-column>
                <el-table-column prop="proc_pur_total" label="进货金额" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_total ? Number(scope.row.proc_pur_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="purd_instockOK_num" label="已入库" width="100"></el-table-column>
                <el-table-column label="未入库" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_num - scope.row.purd_instockOK_num }}
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="productDialogVisible = false">取消</el-button>
                <el-button type="success" @click="confirmProductSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted,computed} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import { useRouter } from 'vue-router';//路由
import { ArrowDown } from '@element-plus/icons-vue';

export default {
    components: {
        ArrowDown
    },
    setup(){

        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

         //规则验证
         const rules = reactive({
            date:[
                { required: true, message: '请选择退货日期', trigger: 'blur' },
            ],
            purcode:[
                { required: true, message: '请选择进货单', trigger: 'blur' },
            ],
            reason:[
                { required: true, message: '请输入退货原因', trigger: 'blur' },
            ]
        });

        //日期转换格式
        function formatDateTime(date) {
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const seconds = String(d.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
         // 状态映射计算属性
         const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });


        //表单信息
        const purtref=ref("");
        const purtform=reactive({
            code:"",
            date:"",
            purid:0,
            purcode: "",
            purdate:"",//进货日期
            purtotal:"",//进货金额
            purnum:"",//进货数量
            supid: 0,
            supname:"",
            suplink:"",
            supphone:"",
            deptid:0,
            deptname:"",
            userid:0,
            username:"",
            reason: "",
            remark:"",
        })

        
        //#region 上传附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }
        //#endregion

        //#region 选择进货单
        const purchaseOrderDialogVisible = ref(false);
        const purdata = ref([]);

        function ShowPurchaseOrderDialog() {
            purchaseOrderDialogVisible.value = true;
            PO_All();
        }

        function PO_All() {
            http.get("/Purchase_h/GetAllPurchase_h")
            .then(res => {
                purdata.value = res.data;
                //转换日期格式
                purdata.value.forEach(item => {
                    item.pur_date = formatDateTime(new Date(item.pur_date));
                    //保留两位小数
                    item.pur_total = item.pur_total.toFixed(2);
                    item.pur_status = statusMap.value[item.pur_status] || "未知状态";
                });
            }).catch(err => {
                console.log(err);
            });
        }


        const selectedPO = ref(null); // 选中的进货单
        function selectOrder(val){
            selectedPO.value = val;
        }

        //填充
        async function confirmPurchaseOrderSelection() {
            if (!selectedPO.value) {
                ElMessage.warning('请选择一个进货单');
                return;
            }
            
            // 填充主表单
            const selected = selectedPO.value[0];
            purtform.purid = selected.pur_id;
            purtform.purcode = selected.pur_code;
            purtform.purdate = selected.pur_date;
            purtform.purtotal = selected.pur_total;
            purtform.purnum = selected.pur_num;
            purtform.supid=selected.sup_id;
            purtform.supname=selected.sup_name;
            purtform.suplink = selected.sup_linkman;
            purtform.supphone = selected.sup_linkphone;
            purtform.deptid = selected.pur_depId;
            purtform.deptname = selected.pur_depName;
            purtform.userid = selected.pur_userId;
            purtform.username = selected.pur_userName;

            purchaseOrderDialogVisible.value = false;
        }

        //#endregion

        //#region 选择货品
        const productDialogVisible = ref(false);
        const procdata = ref([]);
        const dialogSelectedProducts = ref([]);

        function ShowProduct() {
            if (!purtform.purid) {
                ElMessage.warning('请先选择一个进货单');
                return;
            }
            productDialogVisible.value = true;
            Search();
        }

        //查询并组合货品详细信息
        async function Search() {
            try {
                // 1. 获取采购单明细
                const res = await http.get("/Purchase_d/GetPurchase_Ds?purid=" + purtform.purid);
                const purchaseDetails = res.data;

                if (!purchaseDetails || purchaseDetails.length === 0) {
                    procdata.value = [];
                    return;
                }

                // 2. 为每个明细项创建一个获取完整货品信息的Promise
                const productPromises = purchaseDetails.map(item =>
                    http.get(`/Product/GetProductById?id=${item.proc_id}`)
                );

                // 3. 等待所有货品信息请求完成
                const productResponses = await Promise.all(productPromises);
                const products = productResponses.map(response => response.data);

                // 4. 将采购明细与完整的货品信息合并
                procdata.value = purchaseDetails.map(detail => {
                    const productInfo = products.find(p => p.proc_id === detail.proc_id);
                    return {
                        ...detail,        // 采购明细信息
                        ...(productInfo || {}), // 完整的货品信息
                        // 确保使用采购单的原始价格和数量
                        proc_pur_price: detail.proc_pur_price,
                        proc_pur_num: detail.proc_pur_num,
                        proc_pur_total: detail.proc_pur_total,
                    };
                });

            } catch (err) {
                console.error("加载进货货品明细失败:", err);
                ElMessage.error("加载进货货品明细失败");
                procdata.value = [];
            }
        }

        // 控制表格行是否可选
        function isSelectable(row) {
            // 如果货品已在主列表中，则不可勾选
            return !selectedProducts.value.some(p => p.proc_id === row.proc_id);
        }
        
        // 弹窗表格选中项变化
        function handleSelectionChange(val) {
            dialogSelectedProducts.value = val;
        }

        // 确认选择货品
        function confirmProductSelection() {
            if (dialogSelectedProducts.value.length === 0) {
                ElMessage.warning('请至少选择一个货品');
                return;
            }

            dialogSelectedProducts.value.forEach(product => {
                const isExisting = selectedProducts.value.some(p => p.proc_id === product.proc_id);
                if (!isExisting) {
                    selectedProducts.value.push({
                        ...product,
                        purt_num: 0, // 本次退货数量
                        purt_price: product.proc_pur_price, // 退货单价(取进货价)
                        purt_total: 0, // 退货金额
                        in_stock_num: product.purd_instockOK_num || 0, // 已入库
                        not_in_stock_num: (product.proc_pur_num || 0) - (product.purd_instockOK_num || 0) //未入库
                    });
                }
            });

            productDialogVisible.value = false;
        }
        //#endregion

        // 选中的产品数组
        const selectedProducts = ref([]);
        
        // 计算金额
        function calculateAmount(row) {
            row.purtd_total = (row.purtd_num * row.purt_price).toFixed(2);
        }
        
        // 计算总数量
        function calculateTotalQuantity() {
            if (selectedProducts.value.length === 0) return 0;
            return selectedProducts.value.reduce((total, product) => {
                return total + (product.purtd_num || 0);
            }, 0);
        }
        
        // 计算总金额
        function calculateTotalAmount() {
            if (selectedProducts.value.length === 0) return '0.00';
            const total = selectedProducts.value.reduce((sum, product) => {
                return sum + (parseFloat(product.purtd_total) || 0);
            }, 0);
            return total.toFixed(2);
        }


        // 移除产品
        function removeProduct(procId) {
            // 通过产品ID查找对应的索引位置
            const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
            if (index !== -1) {
                // 找到对应产品后从数组中删除
                selectedProducts.value.splice(index, 1);
            }
        }


        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        //批量移除
        function batchRemoveProducts(){
            if(selectdata.value.length===0){
                ElMessage.warning('请先选择要移除的货品');
                return;
            }
            selectdata.value.forEach(item=>{
                const index=selectedProducts.value.findIndex(p=>p.proc_id===item.proc_id);
                if(index!==-1){
                    selectedProducts.value.splice(index,1);
                }
            });
            ElMessage.success('已移除'+selectdata.value.length+'个货品');
        }

        function tableRowClassName({ row }) {
            if (!row.proc_ky_inventory || row.proc_ky_inventory <= 0) {
                return 'warning-row';
            }
            return '';
        }

        //#region 添加
        async function Add(status = 2) { // 默认状态为2-待审核
            try {
                //1.验证表单
                const [purtValid] = await Promise.all([
                    new Promise(resolve => purtref.value.validate(resolve)),
                ]);
                if (!purtValid) {
                    return false;
                }

                //2.验证必须有货品信息
                if(selectedProducts.value.length === 0) {
                    ElMessage.error('请至少选择一个货品进行退货');
                    return false;
                }
                
                //3.验证退货数量>0
                const hasReturnItems = selectedProducts.value.some(p => p.purtd_num > 0);
                if (!hasReturnItems) {
                    ElMessage.error('请至少输入一个货品的退货数量');
                    return false;
                }

                //4.生成编号
                const codeRes = await http.get("/CodeRule/GeneratedCode?id=20");
                purtform.code = codeRes.data;

                //5.准备添加数据
                //退货单
                const purtdata={
                    purt_code:purtform.code,
                    purt_date:formatDateTime(purtform.date),
                    pur_id:purtform.purid,
                    pur_code:purtform.purcode,
                    sup_id:purtform.supid,
                    sup_name:purtform.supname,
                    sup_linkman:purtform.suplink,
                    sup_linkphone:purtform.supphone,
                    pur_userId:purtform.userid,
                    pur_userName:purtform.username,
                    pur_depId:purtform.deptid,
                    pur_depName:purtform.deptname,
                    purt_categories:selectedProducts.value.length,
                    purt_num:calculateTotalQuantity(),//总数量
                    purt_total:calculateTotalAmount(),//总金额
                    purt_outstockOK_num:0,//已出库
                    purt_outstockNO_num:calculateTotalQuantity(),//未出库
                    purt_reason: purtform.reason,
                    remark:purtform.remark,
                    purt_status:status, // 使用传入的状态值
                    create_name:user.name,
                    create_time:formatDateTime(new Date()),
                }

                //退货明细单
                const purtdetaildata=selectedProducts.value.map(item=>{
                    return{
                        purt_id:0,
                        purd_id:item.purd_id,
                        proc_id:item.proc_id,
                        proc_name:item.proc_name,
                        purtd_num:item.purtd_num,
                        purtd_price:item.purt_price,
                        purtd_outstockOK_num:0,
                        purtd_outstockNO_num:item.purtd_num,
                        purtd_total:item.purtd_total,
                        remark:item.remark
                    }
                })
                //附件
                const filelistdata = filelist.value.map(item => {
                    return {
                        business_type:"进货退货单",
                        business_code:purtform.code,
                        title: item.originalName,
                        file_name: item.url,
                    }
                })

                 // 将所有数据整合到一个 payload 对象中，用于事务性提交
                let payload = {
                    purtData: purtdata,
                    purtDetails: purtdetaildata,
                    attachments: filelistdata
                };

                console.log("发往后端的完整数据包 (Payload):", payload);
                const res = await http.post("/PurchaseReturn_h/AddPurchaseReturn_h", payload);
                if (res.data > 0) {
                    ElMessage.success("添加成功");
                    return true;
                } else {
                    ElMessage.error("添加失败");
                    return false;
                }
            } catch (err) {
                console.log(err);
                ElMessage.error('添加失败');
                return false;
            }
        } 
        //#endregion

        //保存为草稿
        async function SaveAsDraft() {
            const result = await Add(1); // 传入状态 1 表示草稿
            if (result) {
                router.push("purchasereturn");
            }
        }
        
        //保存
        async function OK() {
            const result = await Add(2); // 传入状态 2 表示待审核
            if (result) {
                router.push("purchasereturn");
            }
        }

        //保存并新增
        async function OKAdd(){
            const result = await Add(2); // 传入状态 2 表示待审核
            if(result){
                //清空
                purtref.value.resetFields();
                selectedProducts.value = [];
            }
        }


        //关闭
        function Close(){
            router.back();
        }

        //挂载
        onMounted(() => {
            GetStatus().then(()=>{
                PO_All();
            });
        });

        return{
            rules,
            Add,
            OK,
            OKAdd,
            Close,
            handleFileSuccess,
            handlePreview,
            headers,
            filelist,
            purtform,
            purtref,
            selectedProducts,
            removeProduct,
            calculateAmount,
            calculateTotalQuantity,
            calculateTotalAmount,
            SaveAsDraft,
            SelectChange,
            batchRemoveProducts,
            selectdata,
            handleRemove,
            tableRowClassName,
            purchaseOrderDialogVisible,
            purdata,
            ShowPurchaseOrderDialog,
            selectOrder,
            confirmPurchaseOrderSelection,
            ShowProduct,
            productDialogVisible,
            Search,
            procdata,
            GetStatus,
            statusMap,
            isSelectable,
            handleSelectionChange,
            confirmProductSelection
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    /* 模态框样式 */
    :deep(.el-dialog__body) {
        padding: 10px 20px;
    }
    
    :deep(.el-dialog__footer) {
        border-top: 1px solid #e6e6e6;
        padding: 10px 0;
    }
    
    :deep(.el-dialog__header) {
        border-bottom: 1px solid #e6e6e6;
    }

    :deep(.el-table .warning-row) {
        background: #fef0f0 !important;
    }

    :deep(.el-table .warning-row > td) {
        background: #fef0f0 !important;
    }
</style>